package com.atguigu.cart.controller;

import com.atguigu.cart.service.CartService;
import com.atguigu.cart.vo.Cart;
import com.atguigu.cart.vo.CartItem;
import com.atguigu.common.utils.R;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ExecutionException;

@Controller
@RequestMapping
public class CartPageController {
    @Resource
    private CartService cartService;

    @GetMapping("/cart.html")
    public String page(){
        return "cartList";
    }

    @GetMapping("/getCarts")
    public String getCarts(Model model) throws ExecutionException, InterruptedException {
        Cart cart = cartService.getCarts();
        model.addAttribute("carts", cart);
        return "cartList";
    }

    @GetMapping("/addToCart")
    public String addToCart(Long skuId, Integer num, RedirectAttributes attributes) throws ExecutionException, InterruptedException {
        //把商品加入到购物车中,即放入到reids中保存
        CartItem cartItem = cartService.addToCart(skuId, num);
        attributes.addAttribute("skuId", skuId);
        return "redirect:http://cart.gulimall.com/addCartSuccess";
    }

    @GetMapping("/addCartSuccess")
    public String addCartSuccess(Long skuId, Model model){
        //查询购物车中商品信息返回给页面
        CartItem item = cartService.getCartItem(skuId);
        model.addAttribute("item", item);
        return "success";
    }

    @ResponseBody
    @GetMapping("/getItems/check")
    public List<CartItem> getCheckItemList(){
        List<CartItem> result = cartService.getCheckItems();
        return result;
    }
}
